package com.dynamic.redis.config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;

import java.net.URI;
import java.net.URISyntaxException;

public abstract class RedisConnectionConfiguration {

    /**
     * redis配置properties
     */
    private final RedisProperties properties;

    public int getDatabase() {
        return database;
    }

    private final int database;

    protected RedisConnectionConfiguration(RedisProperties properties,
                                           int database) {
        this.properties = properties;
        this.database = database;
    }


    /**
     * 解析Redis url连接，创建连接信息
     */
    protected static ConnectionInfo parseUrl(String url) {
        try {
            URI uri = new URI(url);
            String scheme = uri.getScheme();
            if (!"redis".equals(scheme) && !"rediss".equals(scheme)) {
                // 无效的或畸形的url
                throw new RuntimeException(url);
            }
            boolean useSsl = ("rediss".equals(scheme));
            String username = null;
            String password = null;
            if (uri.getUserInfo() != null) {
                String candidate = uri.getUserInfo();
                int index = candidate.indexOf(':');
                if (index >= 0) {
                    username = candidate.substring(0, index);
                    password = candidate.substring(index + 1);
                } else {
                    password = candidate;
                }
            }
            return new ConnectionInfo(uri, useSsl, username, password);
        } catch (URISyntaxException ex) {
            // 无效的或畸形的url
            throw new RuntimeException("Malformed url '" + url + "'", ex);
        }
    }




    protected final RedisProperties getProperties() {
        return properties;
    }
    /**
     * Redis连接信息
     */
    static class ConnectionInfo {

        private final URI uri;

        private final boolean useSsl;

        private final String username;

        private final String password;

        ConnectionInfo(URI uri, boolean useSsl, String username, String password) {
            this.uri = uri;
            this.useSsl = useSsl;
            this.username = username;
            this.password = password;
        }

        boolean isUseSsl() {
            return useSsl;
        }

        String getHostName() {
            return uri.getHost();
        }

        int getPort() {
            return uri.getPort();
        }

        String getUsername() {
            return username;
        }

        String getPassword() {
            return password;
        }

    }

}
